let axios = require('axios')
let _ = require('lodash')

const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate
let collect_fund = db.collection('fund')

exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ', event)

  let code = event.code
  if (_.isNil(code)) {
    return 'error:code is nil'
  }
  // http://fund.eastmoney.com/pingzhongdata/${code}.js?v=20211105230732
  let jsInfoGet = await axios.get(`http://fund.eastmoney.com/pingzhongdata/${code}.js`)

  if (jsInfoGet.status === 200) {
    let jsInfoStr = jsInfoGet.data
    eval(jsInfoStr)
    let info = {
      name: fS_name,
      code: fS_code,
      grandTotal: Data_grandTotal,
      updateTime: new Date().getTime(),
    }
    if (fS_code !== code) {
      return 'error:code is not eq fS_code'
    }

    // 是否已经存在此基金的数据,无:新增,有:依据_id更新
    let findInfo = await collect_fund.where({
      code: fS_code,
    }).get()

    let resOpt
    if (_.size(findInfo.data) > 0) {
      let changeInfo = findInfo.data[0]
      console.log(`已经有数据`, changeInfo.id)
      resOpt = await collect_fund.doc(changeInfo._id).update(info)
    } else {
      resOpt = await collect_fund.add(info)
    }
    console.log(`resOpt`, resOpt)
  }

  //返回数据给客户端
  return event
}
